<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    :isDetail="false"
    :width="getIsMobile ? '95%':'80%'"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #tag="{ model, field }">
        <Row class="mb-4" :gutter="24" v-for="(item, index) in state.nodes" :key="index">
          <Col :span="20">
            <Tag
              class="large"
              size="large"
              v-if="state.isShow"
              v-for="(it, ix) in item"
              :color="it.color"
              :closable="true"
              :key="ix"
              @click="showInput(index, ix, it)"
              @close="tagClose(index, it)"
            >
              {{ it.title }}
            </Tag>

            <Tag
              class="large"
              size="large"
              v-if="item.length < state.rowMaxLength"
              @click="showInput(index, 0)"
              style="border-style: dashed; background: #fff"
            >
              <plus-outlined /> 创建新链接
            </Tag>
          </Col>
          <Col :span="4">
            <a-button size="small" danger v-if="index > 0" @click="() => del(index)">-</a-button>
          </Col>
        </Row>
      </template>
      <template #add="{ model, field }">
        <a-button type="primary" size="small" v-if="Number(field) === 0" @click="batchAdd">
          +
        </a-button>
      </template>
    </BasicForm>
    <LinkModal @register="registerModal" @success="handleLinkSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive, nextTick } from 'vue';
  import { useAppInject } from '@/hooks/web/useAppInject';
  import { Tag, Row, Col } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './noticeboard.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { useModal } from '@/components/Modal';
  import LinkModal from './LinkModal.vue';

  import { getMenuList } from '@/api/demo/system';

  const { getIsMobile } = useAppInject();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const state = reactive({
    rowMaxLength: 5,
    rowIndex: 0,
    colIndex: 0,
    isAdd: true,
    isShow: true,
    nodes: [[]],
  });
  // const treeData = ref<TreeItem[]>([]);
  const [registerModal, { openModal }] = useModal();
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    actionColOptions: { span: 24 },
    baseColProps: { span: 8 },

    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    // if (unref(treeData).length === 0) {
    //   treeData.value = (await getMenuList()) as any as TreeItem[];
    // }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增布告栏' : '编辑布告栏'));

  async function handleSubmit() {
    setFieldsValue({ tag: JSON.stringify(state.nodes) });
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  const showInput = (rowIndex, colIndex, item) => {
    state.rowIndex = rowIndex;
    state.colIndex = colIndex;
    state.isAdd = item == null;

    openModal(true, {
      record: item,
      isUpdate: item != null,
    });
  };

  function handleLinkSuccess(record) {
    if (state.isAdd) {
      state.nodes[state.rowIndex].push(record);
    } else {
      state.nodes[state.rowIndex][state.colIndex] = record;
    }
    // reload();
  }

  function tagClose(rowIndex, item) {
    state.isShow = false;
    const tags = state.nodes[rowIndex].filter((tag) => tag !== item);
    state.nodes[rowIndex] = tags;
    nextTick(() => {
      state.isShow = true;
    });
  }

  function batchAdd() {
    state.nodes.push([]);
  }

  function del(field: number) {
    state.nodes.splice(field, 1);
  }
</script>
<style scoped>
  .ant-tag.large {
    padding: 5px 12px;
  }
</style>
